<script setup lang="ts">
import dayjs from 'dayjs'
import { useUserInfoStore } from '@/store/userInfo'
import useHomeBarHeight from '@/composables/homeBarHeight'
import { validateCouponAPI } from '@/apis/validateCoupon'
import { fetchValidateCouponDetailAPI } from '@/apis/fetchValidateCouponDetail'

import dialogIcon from '@/static/images/checkmark_colorful.png'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const homeBarHeight = useHomeBarHeight()

const loading = ref(false)
const detail = ref<CouponDetail | null>(null)

const isShowSuccessDialog = ref(false)

onLoad(async (options) => {
  if (!userInfoStore.userInfo?.token) {
    router.replaceAll('/pages/index')
    return
  }

  // 扫太阳码进来
  if (options && options.id) {
    try {
      loading.value = true
      const res = await fetchValidateCouponDetailAPI({ id: options.id }, userInfoStore.userInfo!.token!)
      if (res.data?.code === 1) {
        detail.value = res.data.data
        loading.value = true
      }
      else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
    }
    catch (err) {
      uni.showToast({ title: JSON.stringify(err), icon: 'none' })
    }
  }

  // 扫普通码进来（废弃）
  if (options && options.q) {
    function extractIdFromUrl(encodedUrl: string) {
      const url = decodeURIComponent(encodedUrl)

      // 找到最后一个"/"的位置
      const lastIndex = url.lastIndexOf('/')

      // 提取最后一个"/"之后的内容
      const id = url.substring(lastIndex + 1)

      return id
    }

    try {
      loading.value = true
      const res = await fetchValidateCouponDetailAPI({ id: extractIdFromUrl(options.q) }, userInfoStore.userInfo!.token!)
      if (res.data?.code === 1) {
        detail.value = res.data.data
        loading.value = true
      }
      else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
    }
    catch (err) {
      uni.showToast({ title: JSON.stringify(err), icon: 'none' })
    }
  }
})

const classificateName = computed(() => {
  if (detail.value)
    return ['新人券', '员工券', '普通券'][detail.value.classificate! - 1]
  else
    return '未知'
})

async function handleValidateCoupon() {
  uni.showLoading({ title: '加载中...' })
  const res = await validateCouponAPI({ id: detail.value?.id ? `${detail.value?.id}` : '' }, userInfoStore.userInfo!.token!)
  if (res.data?.code === 1)
    isShowSuccessDialog.value = true
  else
    uni.showModal({ title: res.data?.msg, icon: 'none', showCancel: false })
  uni.hideLoading()
}

function handleExit() {
  router.replaceAll('/pages/index')
}
</script>

<template>
  <view class="absolute left-0 top-0 h-990rpx w-screen from-#4999F7 to-#78D9FE to-opacity-0 bg-gradient-to-b" />
  <view class="relative z-10 flex flex-col items-center">
    <Spacer height="70" />
    <image
      class="h-100rpx w-100rpx"
      src="@/static/images/redeem_coupon.png"
    />
    <Spacer height="22" />
    <view class="text-40rpx text-white font-semibold leading-56rpx">
      核销优惠券
    </view>
    <Spacer height="4" />
    <view class="text-28rpx text-white leading-40rpx">
      确认是否核销以下优惠券
    </view>
    <Spacer height="60" />
    <view class="relative z-1 mx-44rpx flex flex-col items-center overflow-hidden rounded-20rpx bg-white">
      <view class="flex items-center">
        <view class="h-186rpx w-210rpx flex flex-col items-center justify-center">
          <view v-if="detail?.type.toString() === '1'" class="flex items-baseline">
            <view class="text-42rpx text-#333333 font-semibold">
              ¥
            </view>
            <view class="text-60rpx text-#333333 font-semibold leading-80rpx">
              {{ detail.complete_money || '0' }}
            </view>
          </view>
          <view v-else>
            <view class="text-60rpx text-#333333 font-semibold leading-80rpx">
              {{ detail?.discount || '0' }}折
            </view>
          </view>
          <view class="text-20rpx text-#333333 font-semibold leading-28rpx">
            满{{ detail?.money || '0' }}元可用
          </view>
        </view>
        <view class="h-92rpx w-2rpx bg-#333333 bg-opacity-20" />
        <view class="h-186rpx w-450rpx flex flex-col justify-center px-54rpx">
          <view class="text-32rpx text-#333333 font-semibold leading-42rpx">
            {{ classificateName || '未知' }}
          </view>
          <Spacer height="8" />
          <view class="text-24rpx text-#333333 font-semibold leading-32rpx">
            有效期 {{ dayjs(detail?.validate_start_time).format('YYYY-MM-DD') || '未知' }}-{{ dayjs(detail?.validate_start_time).format('YYYY-MM-DD') || '未知' }}
          </view>
        </view>
      </view>
      <Divider width="582" color="#333333" />
      <Spacer height="80" />
      <view class="w-full px-40rpx">
        <view class="flex">
          <view class="text-24rpx text-#333333 font-medium leading-32rpx">
            券码：
          </view>
          <view class="text-24rpx text-#848484 leading-32rpx">
            {{ detail?.coupon_num || '未知' }}
          </view>
        </view>
        <Spacer height="24" />
        <view class="flex">
          <view class="text-24rpx text-#333333 font-medium leading-32rpx">
            领取时间：
          </view>
          <view class="text-24rpx text-#848484 leading-32rpx">
            {{ detail?.create_time || '未知' }}
          </view>
        </view>
        <Spacer height="24" />
        <view class="flex">
          <view class="flex-shrink-0 text-24rpx text-#333333 font-medium leading-32rpx">
            使用说明：
          </view>
          <view class="text-24rpx text-#848484 leading-32rpx">
            {{ detail?.explain }}
          </view>
        </view>
      </view>
      <!-- 两个半圆 看起来像裁剪了卡片 -->
      <view class="absolute top-171rpx h-32rpx w-32rpx rounded-full bg-#A7CCF7 -left-16rpx" />
      <view class="absolute top-171rpx h-32rpx w-32rpx rounded-full bg-#A7CCF7 -right-16rpx" />
      <Spacer height="76" />
    </view>
  </view>
  <view
    class="fixed bottom-0 w-750rpx flex items-center justify-center bg-white px-24rpx pt-20rpx x-center"
    :style="{ paddingBottom: `${homeBarHeight}px` }"
  >
    <button class="h-96rpx w-702rpx flex items-center justify-center rounded-full bg-#4999F7" @tap="handleValidateCoupon">
      <view class="text-28rpx text-white leading-40rpx">
        确认核销
      </view>
    </button>
  </view>
  <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
  <uv-overlay :show="isShowSuccessDialog" @tap="isShowSuccessDialog = false">
    <uv-transition mode="zoom-in" :show="isShowSuccessDialog">
      <view class="relative h-screen w-screen">
        <Dialog
          :icon="dialogIcon"
          title="核销成功"
          :content="`优惠券${detail?.coupon_num}已核销成功`"
          hide-cancel-button
          confirm-label="返回首页"
          @confirm="handleExit"
        />
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'validateCoupon'
style:
  navigationBarTitleText: '核销优惠券'
</route>
